package com.heima.search.service.impl;

import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.es.ArticleRepository;
import com.heima.search.service.IApUserSearchService;
import com.heima.search.service.IArticleSearchService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;

/**
 * @Author WSJ
 * @Date 2022-03-26-19:52
 * @Version 1.0 （版本号）
 */
@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {
    @Autowired
    private ArticleRepository repository;
    @Autowired
    private IApUserSearchService apUserSearchService;
    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        //页面查询列表
        //判断关键字是否为空，为空返回空集合
        if (dto==null|| StringUtils.isEmpty(dto.getSearchWords())) {
            return ResponseResult.okResult(new ArrayList<>());
        }
        //分页模糊查询
        Pageable page=PageRequest.of(dto.getPage().intValue()-1,dto.getSize(), Sort.Direction.DESC,"publishTime");
        QueryBuilder queryBuilder = QueryBuilders.matchQuery("title", dto.getSearchWords());
        Page<ApArticleSearch> search = repository.search(queryBuilder, page);
        //调用异步线程保存记录
        User user = AppThreadLocalUtil.get();
        Integer userId=null;
        if (user!=null) {
            userId = user.getId();
        }
        apUserSearchService.saveSearchRecord(dto.getSearchWords(), userId, dto.getEquipmentId());
        //返回分页响应
        return new PageResponseResult(dto.getPage(), dto.getSize(), search.getTotalElements(), search.getContent());
    }
}
